package com.boot.dcg;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

/**
 * @author songlin.an
 * @className FileUtils
 * @description TODO
 * @date 2023/5/23 20:37
 **/
public class FileUtils {


    public static void uploadResource(String picPath) throws Exception {
        // 云存储环境地址
        String dcgBaseUrl = "http://dcs.dmall.com:8266";
        // 资源Key
        String resourceKey = picPath.substring(picPath.lastIndexOf("\\") + 1);
        // 生成Token
        String token =
                DCGSign.builder("6PC9JuemdHGvcet0unaPmEJ3srngUJvv", "VUl2TmYdNFHpYQ05G8tqY2G6Ou7OYJB08m3qGHS5").build().signToken(resourceKey);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        URL baseUrl = new URL(dcgBaseUrl);
        URI uri = new URIBuilder().setScheme(baseUrl.getProtocol()).setHost(baseUrl.getHost()).setPort(baseUrl.getPort())
                .setPath("/file/upload")
                .setParameter("resourceKey", resourceKey).build();
        HttpPost httpPost = new HttpPost(uri);
        // 设置token
        httpPost.setHeader("Authorization", token);
        CloseableHttpResponse response = null;
        try {
            FileEntity fileEntity = new FileEntity(new File(picPath));
            httpPost.setEntity(fileEntity);
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (null != responseEntity) {
                System.out.println("body: " + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void queryResourceAddress() throws Exception {
        // 云存储环境地址
        String dcgBaseUrl = "http://dcs.dmall.com:8266";
        // 资源Key
        String resourceKey = "dddd.jfif";
        // 生成Token
        String token =
                DCGSign.builder("6PC9JuemdHGvcet0unaPmEJ3srngUJvv", "VUl2TmYdNFHpYQ05G8tqY2G6Ou7OYJB08m3qGHS5").build().signToken(resourceKey);

        URL baseUrl = new URL(dcgBaseUrl);
        URI uri = new URIBuilder().setScheme(baseUrl.getProtocol()).setHost(baseUrl.getHost()).setPort(baseUrl.getPort())
                .setPath("/resource/address")
                .setParameter("resourceKeys", resourceKey)
                .build();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(uri);
        // 设置token，也可放到param里面
        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            if (null != responseEntity) {
                System.out.println("body: " + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void queryAll() throws Exception {
        // 云存储环境地址
        String dcgBaseUrl = "http://dcs.dmall.com:8266";
        // 资源Key
        String resourceKey = "dddd.jfif";
        // 生成Token
        String token =
                DCGSign.builder("6PC9JuemdHGvcet0unaPmEJ3srngUJvv", "VUl2TmYdNFHpYQ05G8tqY2G6Ou7OYJB08m3qGHS5").build().signToken(resourceKey);

        URL baseUrl = new URL(dcgBaseUrl);
        URI uri = new URIBuilder().setScheme(baseUrl.getProtocol()).setHost(baseUrl.getHost()).setPort(baseUrl.getPort())
                .setPath("/resource")
                .setParameter("limit", "50")
                .build();

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(uri);
        // 设置token，也可放到param里面
        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            if (null != responseEntity) {
                System.out.println("body: " + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        uploadResource("D:\\bankIcon\\bak\\ycsbcardfront01.png");
//        queryResourceAddress();
//        queryAll();

//        List<String> files = getFiles("D:\\bankIcon\\bak\\1");
//        for (String file : files) {
//            uploadResource(file);
//        }

//        queryAll();
        String oldPromotionInfo = "{\"promotionDetail\":{\"disFee\":0,\"skuDisFee\":850,\"disMerchant\":0,\"disPlatform\":0,\"skuDisDetail\":[{\"num\":1,\"skuNo\":\"6907201110894\",\"barType\":2,\"disAmount\":850}],\"skuDisMerchant\":425,\"skuDisPlatform\":425},\"payPromotionType\":1,\"payPromotionSubType\":1}";
        String newPromotionInfo = "{\"discountFee\":0,\"skuDiscountFee\":880,\"skuDiscountDetail\":[{\"price\":880,\"skuNo\":\"6975682482601\",\"quantity\":1,\"barCodeType\":2,\"discountAmount\":880}],\"discountOtherContribute\":0,\"discountMerchantContribute\":0,\"discountPlatformContribute\":0,\"skuDiscountOtherContribute\":0,\"skuDiscountMerchantContribute\":435,\"skuDiscountPlatformContribute\":445}";

        System.out.println(test11(oldPromotionInfo, newPromotionInfo));

    }


    public static String test11(String oldPromotionInfo,String newPromotionInfo) {
        if (!StringUtils.isEmpty(oldPromotionInfo)) {
            JSONObject oldJsonObject = JSONObject.parseObject(oldPromotionInfo);
            if (!StringUtils.isEmpty(newPromotionInfo)) {
                JSONObject newJsonObject = JSONObject.parseObject(newPromotionInfo);
                oldJsonObject.putAll(newJsonObject);
                return oldJsonObject.toJSONString();
            }
        }
        return null;
    }


    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }
}
